//
//  UIApplication+AppRootViewController.m
//  GeeHome
//
//  Created by Duncan on 2018/9/10.
//  Copyright © 2018年 WaterWorld. All rights reserved.
//

#import "UIApplication+AppRootViewController.h"

@implementation UIApplication (AppRootViewController)

+ (UIViewController *)currentRootTopViewController {
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    if (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}

// 这个方法才能获取到最终的topViewController
+ (UIViewController *)currentViewController {
    UIViewController *vc = [self currentRootTopViewController];
    return [self findTopViewControllerWithCtl:vc];
}

+ (UIViewController *)findTopViewControllerWithCtl:(UIViewController *)vc {
    
    if ([vc isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabVC = (UITabBarController *)vc;
        UIViewController *ctl = tabVC.selectedViewController;
        
        if ([ctl isKindOfClass:[UINavigationController class]]) {
            return ((UINavigationController *)ctl).visibleViewController;
        } else {
            return vc.presentedViewController ? vc.presentedViewController : vc;
        }
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        return ((UINavigationController *)vc).visibleViewController;
    } else {
        return vc.presentedViewController ? vc.presentedViewController : vc;
    }
}

//// 获取当前活动的navigationcontroller
//- (UINavigationController *)navigationViewController {
//    UIWindow *window = [UIApplication sharedApplication].keyWindow;
//    if ([window.rootViewController isKindOfClass:[UINavigationController class]])
//    {
//        return (UINavigationController *)window.rootViewController;
//    }
//    else if ([window.rootViewController isKindOfClass:[UITabBarController class]])
//    {
//        UIViewController *selectVc = [((UITabBarController *)window.rootViewController) selectedViewController];
//        if ([selectVc isKindOfClass:[UINavigationController class]])
//        {
//            return (UINavigationController *)selectVc;
//        }
//    }
//    return nil;
//}

- (void)clearLaunchScreenCache {
    NSError *error;
    [NSFileManager.defaultManager removeItemAtPath:[NSString stringWithFormat:@"%@/Library/SplashBoard", NSHomeDirectory()] error:&error];
    if (error) {
        DEBUGLOG(@"Failed to delete aunch screen cache:%@", error);
    } else {
        DEBUGLOG(@"清楚缓存成功");
    }
}

@end
